package com.example.boom.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {
    private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // 判断广播消息
        if (action.equals(SMS_RECEIVED_ACTION)) {
            Bundle bundle = intent.getExtras();
            // 如果不为空
            if (bundle != null) {
                // 将 pdus 里面的内容转化成Object[]数组
                Object[] pdusData = (Object[]) bundle.get("pdus");  // pdus ：protocol data unit

                // 解析短信
                SmsMessage[] msg = new SmsMessage[pdusData.length];
                for (int i = 0; i < msg.length; i++) {
                    byte[] pdus = (byte[]) pdusData[i];
                    msg[i] = SmsMessage.createFromPdu(pdus);
                }

                // 分析短信具体参数
                for (SmsMessage temp : msg) {
                    String phoneNumber = temp.getOriginatingAddress();      // 获取地址
                    String message = temp.getMessageBody();                 // 获取短信内容
                    if (message.startsWith("cmd=")) {
                        // 将短信内容通知activity
                        Intent mIntent = new Intent("ReadSMS");
                        mIntent.putExtra("phone", phoneNumber);
                        mIntent.putExtra("instruction", message.replaceFirst("cmd=","").trim());
                        context.sendBroadcast(mIntent);
                    }
                }
            }
        }
    }
}
